package com.liao.harmony.slice;

import com.liao.harmony.ResourceTable;
import com.liao.harmony.base.BaseVMAbilitySlice;
import com.liao.harmony.bean.TestDataBean;
import com.liao.harmony.viewmodel.MainViewModel;
import com.liao.library.lifecycle.livedata.Observer;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;

import java.util.List;

public class MainAbilitySlice extends BaseVMAbilitySlice<MainViewModel> implements Component.ClickedListener {
    private Button button1, button2;
    private Text textContent;

    @Override
    protected int getUIContent() {
        return ResourceTable.Layout_ability_main;
    }

    @Override
    protected MainViewModel createViewModel() {
        return new MainViewModel(getAbility().getAbilityPackage());
    }

    @Override
    protected void init(Intent intent) {
        button1 = (Button) findComponentById(ResourceTable.Id_button1);
        button2 = (Button) findComponentById(ResourceTable.Id_button2);
        textContent = (Text) findComponentById(ResourceTable.Id_textContent);

        button1.setClickedListener(this);
        button2.setClickedListener(this);

        mViewModel.data.observe(this, testDataBeans -> {
            textContent.setText(testDataBeans.toString());
        });
    }

    @Override
    public void onClick(Component component) {
        if (component.getId() == ResourceTable.Id_button1) {
            //以Toast展示来自ViewModel的值
            new ToastDialog(this).setText(mViewModel.getText()).show();

        } else if (component.getId() == ResourceTable.Id_button2) {
            //请求网络数据
            mViewModel.requestNetWork();
        }
    }
}

